from game_agent import GameAgent
#from agent_english import AgentEnglish

from random import randint
#from match import runMatch
from anytime_alpha_beta import AnyTimeAlphaBetaSearch
from linear import linearEvaluator 
from time import strftime

from z_match import TestMatch

class RandomAgent(GameAgent):
    def move(self, game_state):
        successors = game_state.getSuccessors().keys()
        return successors[randint(0,len(successors)-1)]

    def setup(self, player, game_state, turn_time_limit, setup_time_limit):
        pass

class AgentBond(GameAgent):
    '''
    AlphaBeta
    utility: linearEvaluator
    '''
    def move(self, game_state):
        return self.alphaBeta.search(game_state)

    def setup(self, player, game_state, turn_time_limit, setup_time_limit):
        self.player = player
        u = lambda state, endTime: self.utility(state, endTime)
        self.alphaBeta = AnyTimeAlphaBetaSearch(self.player, 1, u, turn_time_limit)
    
    def utility(self, state, endTime):
        return linearEvaluator(self, state, self.player, endTime)

def TestBattle(agent1, agent2): 
    boardSizes = [5, 6, 8]#10, 20, 30]
    turnLimits = [70]
    turnTimes = [0.2, 5, 10, 20] 
    setupTime = 0.1
    results = []
    for size in boardSizes:
        for turnLimit in turnLimits:
            for timeLimit in turnTimes:
                match1, match2 = TestMatch(agent1, agent2, size, turnLimit, timeLimit, setupTime)
                print strftime(' %H:%M:%S '), "\tDone with "+str((size,turnLimit,timeLimit)),"\t", match1,"\t",match2
                line = (match1[0],match1[1],match2[0],match2[1],size,timeLimit)
                results.append(line)
    return results

def TestTournament(agent1, agent2): 
    boardSizes = [8]
    turnLimits = [100]
    turnTimes = [10] 
    setupTime = 0.1
    results = []
    for size in boardSizes:
        for turnLimit in turnLimits:
            for timeLimit in turnTimes:
                match1, match2 = TestMatch(agent1, agent2, size, turnLimit, timeLimit, setupTime)
                print strftime(' %H:%M:%S '), "\tDone with "+str((size,turnLimit,timeLimit)),"\t", match1,"\t",match2
                line = (match1[0],match1[1],match2[0],match2[1],size,timeLimit)
                results.append(line)
    return results

def TestLogResults(agent1, agent2, filename, type):
    if "battle" == type: results = TestBattle(agent1, agent2)
    else: results = TestTournament(agent1, agent2)
    f = open(filename,"a")
    f.write("Agent1 White\tAgent2 Black\tAgent1 Black\tAgent2 White\t\tBoard Size\tTime Limit\n")    
    f.close()
    for line in results:
        f = open(filename,"a")
        f.write(str(line[0])+"\t"+\
                str(line[1])+"\t"+\
                str(line[2])+"\t"+\
                str(line[3])+"\t\t"+\
                str(line[4])+"\t"+\
                str(line[5])+"\n")
        f.close()